const express = require('express');
const router = express.Router();
const { Article } = require('../../models');
const { Op } = require('sequelize');
const { NotFoundError, success, fail } = require('../../utils/response')

/**
 * 公共方法 查询文章
 */
async function getArticle(req) {
    const { id } = req.params;
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID: ${id}的文章未找到。`)
    }

    return article;
}


/** 查询文章列表
 * GET /amdin/articles
 */

router.get('/', async function (req, res, next) {
    try {
        const { title, currentPage, pageSize } = req.query;
        const _currentPage = Math.abs(Number(currentPage)) || 1;
        const _pageSize = Math.abs(Number(pageSize)) || 10;

        const condition = {
            order: [['id', 'DESC']],
            limit: _pageSize || 10,
            offset: (_currentPage - 1) * _pageSize || 0
        }
        if (title) {
            condition.where = {
                title: {
                    [Op.like]: `%${title}%`
                }
            }
        }
        // const article = await Article.findAll(condition);
        const { count, rows } = await Article.findAndCountAll(condition);
        success(res, '查询文章列表成功', { article: rows, total: count })

    } catch (error) {
        fail(res, error)
    }
});

/** 查询文章详情
 * GET /amdin/articles/:id
 */

router.get('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req);
        success(res, '查询文章详情成功', article)

    } catch (error) {
        fail(res, error)
    }
});

/**
 * 创建文章
 * POST /admin/articles
 */
router.post('/', async function (req, res, next) {
    try {
        const { title, content } = req.body;
        const article = await Article.create({
            title,
            content
        });
        success(res, '创建文章成功', article, 201)

    } catch (error) {
        fail(res, error)
    }
});

/**
 * 删除文章
 * DELETE /admin/articles/:id
 */
router.delete('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req);

        await article.destroy();
        success(res, '删除文章成功')
    } catch (error) {
        fail(res, error)
    }
});


/**
 * 更新文章
 * PUT /admin/articles/:id
 */
router.put('/:id', async function (req, res, next) {
    try {
        const { title, content } = req.body;
        const article = await getArticle(req);
        await article.update({ title, content });
        success(res, '文章修改成功')
    } catch (error) {
        fail(res, error)
    }
});


























module.exports = router;
